//
//  YTHomeViewController.m
//  CllForIOS
//
//  Created by qiyun on 2018/3/6.
//  Copyright © 2018年 aRui. All rights reserved.
//

#import "YTHomeViewController.h"

#import "YTHomeCollectionCell.h"
#import "ImagePlayerView.h"
#import "YTHomeMidView.h"
#import "YTLoginVC.h"
#import "YTWebViewVC.h"
#import "YTAdvertVC.h"
#import "SDCycleScrollView.h"
#import "YTMyPersonEdit.h"

#import "YTHomeCell.h"
#import "YTColleLoneCell.h"
#import "YTHcollectionheader.h"
@interface YTHomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource,YTHomeMidViewDelegate,SDCycleScrollViewDelegate>

//视图
@property (strong, nonatomic) SDCycleScrollView *bannerView;
@property (strong, nonatomic) UIView* tableHeadview;
@property (strong, nonatomic) YTHomeMidView* midView;
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic ,strong) UICollectionView * collectionView;
@property (nonatomic ,strong) UICollectionView * HorizontalcollectionView;


//3 数据源
@property (nonatomic, strong) NSArray * titleArray;
@property (nonatomic, strong) NSArray * iconArray;
//1 数据源
@property (nonatomic, strong) NSArray * imageArray;
//2 数据源
@property (nonatomic, strong) NSArray * smallbannerArray;
//5 数据源
@property (nonatomic, strong) NSMutableArray * dictarray;

@end

@implementation YTHomeViewController

-(void)viewWillAppear:(BOOL)animated{
    //第一次显示新特性界面
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (![[defaults objectForKey:@"skipadvisterview"]isEqual:@"1"]) {
        [self presentViewController:[YTAdvertVC new] animated:1 completion:nil];
    }
    [defaults setObject:@"1" forKey:@"skipadvisterview"];
    
    //登录后实名认证问题
    //判断登录状态
    NSMutableDictionary *data = [Tookit getUserCasheInfo];
    NSString*token= [data objectForKey:@"token"];
     NSString*certNo= [data objectForKey:@"certNo"];
    if (token.length>10) {
        if ([certNo isEqual:@"(未认证)"]) {
            NSLog(@"实名认证");
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"实名认证" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"去认证" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                YTMyPersonEdit*vc=[YTMyPersonEdit new];
                vc.hidesBottomBarWhenPushed=YES;
               [self.navigationController pushViewController:vc animated:1];
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alertController addAction:sureAction];
            [alertController addAction:cancelAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleLabel.text=@"赛程";
    self.lineView.hidden=YES;
 
    self.imageArray=@[@"https://qyun88.oss-cn-hangzhou.aliyuncs.com/picture/20180503120105.png",
                      @"https://qyun88.oss-cn-hangzhou.aliyuncs.com/picture/20180503120115.png",
                      @"https://qyun88.oss-cn-hangzhou.aliyuncs.com/picture/20180502181531.png",
                      @"https://qyun88.oss-cn-hangzhou.aliyuncs.com/picture/20180502181541.png"];
    self.titleArray=@[@"竞彩足球",@"竞彩篮球",@"北京单场",@"传统足球",@"大乐透",@"七星彩",@"排列三",@"排列五"];
    self.iconArray=@[@"icon1",@"icon2",@"icon3_unbuy",@"icon4_unbuy", @"icon5_unbuy",@"icon6_unbuy",@"icon7_unbuy",@"icon8_unbuy"];
    self.smallbannerArray=@[@"smallbanner1",@"smallbanner2",@"smallbanner3"];
    
    self.tableHeadview=[[UIView alloc]init];
    [self.tableHeadview addSubview:self.bannerView];
    [self.tableHeadview addSubview:self.HorizontalcollectionView];
    [self.tableHeadview addSubview:self.collectionView];
    [self.tableHeadview addSubview:self.midView];
    [self.tableHeadview setFrame:CGRectMake(0, 0, SCREEN_W, CGRectGetMaxY(self.midView.frame))];
    [self.tableView setTableHeaderView:self.tableHeadview];
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
        self.tabBarController.tabBar.subviews[0].subviews[1].hidden = YES;
    }
    
    [self  loaddata];
    //没退出的话，自动登录
    [self  autoLoginin];
}
-(void)autoLoginin{
    //获取用户名和密码
    NSMutableDictionary *data = [Tookit getUserCasheInfo];
    NSString*account= [data objectForKey:@"account"];
    NSString*autopassword= [data objectForKey:@"autologinpassword"];
    if(account.length>0&&autopassword.length>0){
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        NSDictionary *dicts = @{@"username":account,
                                @"password":autopassword
                                };
        __weak typeof(self) weakSelf = self;
        [SendRequest getinfoDetailWithURL:k_MainUrl(k_User_login) withDictionary:dicts result:^(NSDictionary *result, NSError *error) {
            NSLog(@"获取---%@",result);
            if ([result[@"success"] isEqual:@1] ) {
                NSString*name=@"(未实名)";
                NSString*certNo=@"(未认证)";
                NSString*username=@"";
                
                if (![result[@"data"][@"name"] isEqual:[NSNull null]]) {
                    //字符串为空的情况
                    if ([result[@"data"][@"name"] length]>0) {
                        name=result[@"data"][@"name"];
                    }
                }
                if (![result[@"data"][@"certNo"] isEqual:[NSNull null]]) {
                    if ([result[@"data"][@"certNo"] length]>0) {
                        certNo= [NSString stringWithFormat:@"%@******%@", [result[@"data"][@"certNo"] substringToIndex:1], [result[@"data"][@"certNo"] substringFromIndex:14]];
                    }
                    
                }
                
                
                if (![result[@"data"][@"username"] isEqual:[NSNull null]]) {
                    if ([result[@"data"][@"username"] length]>0) {
                        username=result[@"data"][@"username"];
                    }
                    
                }
                NSString*mobilestr=[result[@"data"][@"mobile"] stringByReplacingCharactersInRange:NSMakeRange(3, 5)  withString:@"*****"];
                
                //数据存本地
                NSDictionary *userdicts = @{@"account":result[@"data"][@"account"],
                                            @"whiteList2":result[@"data"][@"whiteList2"],
                                            @"mobile":mobilestr,
                                            @"password":result[@"data"][@"password"],
                                            @"autologinpassword":autopassword,
                                            @"token":result[@"token"],
                                            @"name":name,
                                            @"certNo":certNo,
                                            @"username":username
                                            };
                [Tookit saveUserCasheInfo:[NSMutableDictionary dictionaryWithDictionary:userdicts]];

                [self dismissViewControllerAnimated:1 completion:nil];
                
            }else{
                PROMPT(result[@"msg"]);
            }
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        }];
    }

}
#pragma mark - 网络请求
-(void)loaddata{
    self.dictarray=[[NSMutableArray alloc]init];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [SendRequest getinfoDetailWithURL:k_NewsUrl(k_User_News) withDictionary:nil result:^(NSDictionary *result, NSError *error) {
        if (result[@"data"]) {
               for (NSDictionary *dic in (NSArray*)result[@"data"]) {
                [self.dictarray addObject:dic];
              }
              dispatch_group_notify(dispatch_group_create(), dispatch_get_main_queue(), ^{
              [self.tableView reloadData];
              });
        }else{
           
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
}
#pragma mark - 视图1
-(SDCycleScrollView*)bannerView{
    if (!_bannerView) {
        _bannerView=[[SDCycleScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, AfW(157))];
        _bannerView.showPageControl = YES;
        _bannerView.autoScroll = YES;
        _bannerView.autoScrollTimeInterval = 3;
        _bannerView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        _bannerView.delegate = self;
        _bannerView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
        _bannerView.imageURLStringsGroup=self.imageArray;
    }
    
    return _bannerView;
}
#pragma mark - 视图2
- (UICollectionView *)HorizontalcollectionView{
    if (!_HorizontalcollectionView) {
        UICollectionViewFlowLayout * flowLayout=[[UICollectionViewFlowLayout alloc]init];
        flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.itemSize=CGSizeMake(AfW(143),AfW(61));
        // flowLayout.sectionInset = UIEdgeInsetsMake(0, 12, 12, 12);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _HorizontalcollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, AfW(157), SCREEN_W, AfW(87)) collectionViewLayout:flowLayout];
        _HorizontalcollectionView.delegate = self;
        _HorizontalcollectionView.dataSource = self;
        _HorizontalcollectionView.tag=1;
        _HorizontalcollectionView.showsHorizontalScrollIndicator = NO;
        _HorizontalcollectionView.backgroundColor = [UIColor whiteColor];
        [_HorizontalcollectionView registerClass:[YTColleLoneCell class] forCellWithReuseIdentifier:@"YTColleLoneCell"];
    }
    return _HorizontalcollectionView;
}
#pragma mark - 视图3
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout * flowLayout=[[UICollectionViewFlowLayout alloc]init];
        flowLayout = [[UICollectionViewFlowLayout alloc]init];
        //        flowLayout.sectionInset = UIEdgeInsetsMake(0, 12, 12, 12);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        //        // 这两句是必须要的
        flowLayout.headerReferenceSize = CGSizeMake(SCREEN_W, AfW(40));
        flowLayout.footerReferenceSize = CGSizeMake(0 ,0);
        flowLayout.minimumLineSpacing=0;
        flowLayout.minimumInteritemSpacing=0;
        flowLayout.sectionInset=UIEdgeInsetsMake(0, 0, 0, 0);
        flowLayout.itemSize=CGSizeMake(SCREEN_W/4,AfW(80));
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, AfW(157)+AfW(3)+AfW(87), SCREEN_W, AfW(200)) collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor whiteColor];
        
        [_collectionView registerClass:[YTHomeCollectionCell class] forCellWithReuseIdentifier:@"YTHomeCollectionCell"];
        [_collectionView registerClass:[YTHcollectionheader  class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[YTHcollectionheader headerViewIdentifier]];
    
        
    }
    return _collectionView;
}
#pragma mark - 视图4
-(YTHomeMidView*)midView{
    if (!_midView) {
        _midView=[[YTHomeMidView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.collectionView.frame), SCREEN_W, AfW(149))];
    }
    return _midView;
}


#pragma mark - banner点击回调
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    if (index==1) {
        //跳m端
        YTWebViewVC*vc=[[YTWebViewVC alloc]init];
        vc.hidesBottomBarWhenPushed=YES;
        vc.urlStr=@"https://m.qyun88.com/lobby/activity.shtml";
        [self.navigationController pushViewController:vc animated:1];
    }
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView.tag==1) {
        return 3;
    }
    return 8;
}

-(UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{

    if (collectionView.tag==1) {
    }else{
        if([kind isEqualToString:UICollectionElementKindSectionHeader]){
            YTHcollectionheader *supplementaryView = [YTHcollectionheader headerViewWithCollectionView:collectionView forIndexPath:indexPath];
            supplementaryView.textLabel.text=@"销量管理";
            return supplementaryView;
        }else if([kind isEqualToString:UICollectionElementKindSectionFooter]) {
//            YTHcollectionheader *supplementaryView = [YTHcollectionheader headerViewWithCollectionView:collectionView forIndexPath:indexPath];
//            supplementaryView.textLabel.text=@"销量管理";
//            return supplementaryView;
        }
    }

    return nil;

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView.tag==1) {
        static NSString * cellID = @"YTColleLoneCell";
        YTColleLoneCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
        cell.longIcon.image=IMAGE(self.smallbannerArray[indexPath.row]);
        return cell;
    }else{
        static NSString * cellID = @"YTHomeCollectionCell";
        YTHomeCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
        cell.iconView.image=IMAGE(self.iconArray[indexPath.row]);
        cell.titleLabel.text=self.titleArray[indexPath.row];
        return cell;
    }

}
    
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //判断登录状态
    NSMutableDictionary *data = [Tookit getUserCasheInfo];
    NSString*token= [data objectForKey:@"token"];
}
#pragma mark - tableview代理和数据源
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, k_statusbarHeight+49, SCREEN_W, SCREEN_H - k_statusbarHeight-49-k_TabBarHeight) style:UITableViewStylePlain];
        _tableView.separatorColor = RGBA(223, 223, 223);
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableFooterView = [UIView new];
        [_tableView registerClass:[YTHomeCell class] forCellReuseIdentifier:@"YTHomeCell"];
        [self.view addSubview:_tableView];

    }
    return _tableView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dictarray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  return AfW(76);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return AfW(34);
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UIView *view1 = [UIView new];
    view1.frame = CGRectMake(0, 0,SCREEN_W , AfW(34));
    view1.backgroundColor = [UIColor clearColor];

    //
    UIImageView*icon=[[UIImageView alloc]init];
    icon.image=IMAGE(@"smallicon");
    [view1 addSubview:icon];
    icon.frame=CGRectMake(12, 12, 16, 14);
    //
    UILabel*sectiontitle=[[UILabel alloc]init];
    sectiontitle.text=@"更多资讯";
    sectiontitle.font=KFONT_medium(13);
    sectiontitle.textColor=RGBA(144, 144, 144);
    [view1 addSubview:sectiontitle];
    sectiontitle.frame=CGRectMake(CGRectGetMaxX(icon.frame)+7, 12, 100, 13);

    return view1;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
  return [UIView new];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellId = @"YTHomeCell";
    YTHomeCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    cell.title.text=self.dictarray[indexPath.row][@"title"];
    cell.destitle.text=self.dictarray[indexPath.row][@"shortTitle"];
    cell.showDateTime.text=self.dictarray[indexPath.row][@"showDateTime"];
    NSString*imagestr=[NSString stringWithFormat:@"homecellimage%ld",indexPath.row+1];
    cell.rightimage.image=IMAGE(imagestr);

    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  
    if (indexPath.section==1) {
        YTWebViewVC*vc=[[YTWebViewVC alloc]init];
        vc.hidesBottomBarWhenPushed=YES;
        vc.urlStr=[NSString stringWithFormat:@"https://m.qyun88.com/find/findList_message.html?id=%@",self.dictarray[indexPath.row][@"id"]];
        [self.navigationController pushViewController:vc animated:1];
    }
}
#pragma mark -
-(void)tologin{
    //初始化iOS8+
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"登录后您可以查看最新资讯" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    //创建按钮
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"登录按钮block");
        YTLoginVC*loginvc=[YTLoginVC new];
        UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:loginvc];
        [self presentViewController:nav animated:1 completion:nil];
    }];
    //取消按钮（只能创建一个）
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消按钮block");
    }];
  
    //将按钮添加到UIAlertController对象上
    [alertController addAction:sureAction];
    [alertController addAction:cancelAction];
   
    //显示弹窗视图控制器
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark YTHomeMidViewDelegate
-(void)pressTheimageWithTag:(NSInteger)tag{
    YTWebViewVC*webvc=[YTWebViewVC new];
    webvc.hidesBottomBarWhenPushed = YES;
    if (tag==1) {
        webvc.urlStr=@"http://live.qyun88.com/live?platform=app";
        [self.navigationController pushViewController:webvc animated:1];
    }else{
        webvc.urlStr=@"http://live.qyun88.com/live/basketball?platform=app";
        [self.navigationController pushViewController:webvc animated:1];
    }
}

@end
